package xyz.penghaonan.p2plib.helper.message;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

import xyz.penghaonan.p2plib.P2PManager;
import xyz.penghaonan.p2plib.helper.sockethelper.SocketBase;

public class MsgSender {
    private static boolean isServer;

    private static Map<Long, SoftReference<IResponseListener>> listenerMap = new HashMap<>();

    public static void initDevice(boolean isServer) {
        MsgSender.isServer = isServer;
    }

    public static boolean sendMsg(IMsg msg, IResponseListener listener) {
        String data = MsgFactory.createMsgText(msg);
        if (data != null) {
            if (msg instanceof BaseRequestMsg) {
                listenerMap.put(((BaseRequestMsg) msg).getId(), new SoftReference<IResponseListener>(listener));
            }
            return getSocket().send(data);
        }
        return false;
    }

    static void onResponse(BaseResponseMsg msg) {
        SoftReference<IResponseListener> ref = listenerMap.get(msg.getRequestId());
        if (ref == null) {
            return;
        }
        listenerMap.remove(msg.getRequestId());
        IResponseListener listener = ref.get();
        if (listener != null) {
            listener.onResponse(msg);
        }
    }

    public interface OnResponseListener {
        void onResponse();
    }

    private static SocketBase getSocket() {
        if (isServer) {
            return P2PManager.getServerSocketHelper();
        } else {
            return P2PManager.getClientSocketHelper();
        }
    }
}
